﻿using CMS.Forms;
using CMS.REST;
using CMS.Util;
using Newtonsoft.Json.Linq;
using System;
using System.Windows.Forms;

namespace CMS.Dialogs
{
    public partial class ChangePasswordDialog : Form
    {
        public ChangePasswordDialog()
        {
            InitializeComponent();
            TB_UserName.Text = LoginDialog.GetInstance().UserName;
        }

        private void Bn_Commit_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(TB_OldPwd.Text))
            {
                MessageBox.Show(this, "必须输入旧密码");
                return;
            }
            if (string.IsNullOrEmpty(TB_NewPwd.Text) || string.IsNullOrEmpty(TB_NewPwd2.Text))
            {
                MessageBox.Show(this, "必须输入两次新密码");
                return;
            }
            if (TB_OldPwd.Text == TB_NewPwd.Text)
            {
                MessageBox.Show(this, "新密码和旧密码不应当一致");
                return;
            }

            if (TB_NewPwd.Text != TB_NewPwd2.Text)
            {
                MessageBox.Show(this, "两次输入的密码必须一致");
                return;
            }

            RESTResponse response = RESTClient.HttpPost("apis/v1/change_password", new JObject()
            {
                {"user_name", TB_UserName.Text},
                {"password", Utils.MD5(TB_OldPwd.Text) },
                {"new_password", Utils.MD5(TB_NewPwd.Text) },
            });
            if (response.IsSuccess)
            {
                MessageBox.Show(this, "修改账号密码成功");
                DialogResult = DialogResult.OK;
            }
            else
            {
                MessageBox.Show(this, "修改密码失败");
            }
        }
    }
}
